/**
 * Copyright (C), 2015-2018, 成都启迪信息技术有限公司
 * FileName: JdbcPaginationHelper
 * Author:   sjkyll
 * Date:     2018-12-06 11:07
 * Description: 分页组件
 * <author>          <time>          <version>          <desc>
 * 作者姓名         修改时间           版本号            描述
 */
package com.cdqidi.smsservice.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

import static java.lang.System.arraycopy;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author sjkyll
 * @create 2018-12-06 11:07
 * @since 1.0.0
 */
@Slf4j
public class JdbcPaginationHelper<T> {


    public Page<T> fetchPage(final JdbcTemplate jdbcTemplate, final String select, final String sqlExceptSelect, final Object[] args,
                             final Pageable pageable,final Class<T> c) {
        String countSql = "select count(*) "+ sqlExceptSelect;
        String dataSql = "select "+ select +" "+ sqlExceptSelect+" limit ?,?";
        // 总记录数据33
        Long totals = jdbcTemplate.queryForObject(countSql, Long.class, args);
        if(null==totals){
            totals = 0L;
        }
        Object[] obj = new Object[args.length + 2];
        arraycopy(args, 0, obj, 0, args.length);
        Integer start = pageable.getPageSize() * pageable.getPageNumber();
        obj[args.length] = start;
        obj[args.length+1] =  pageable.getPageSize();
        // 根据pageNo取一页数据111
        List<T> list = jdbcTemplate.query(dataSql, obj, new BeanPropertyRowMapper<>(c));
        return new PageImpl<>(list,pageable,totals);
    }
}